package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author hql
 * @date 2019-12-10 9:15
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Reference
    private LoginService loginService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 登录的验证操作
     * @param response
     * @param map
     * @return
     */
    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map<String, String> map){
        String telephone = map.get("telephone");
        String validateCode = map.get("validateCode");

        Result result = null;
        try {
            //查询是否存在会员信息，若不存在则注册
            result = loginService.check(telephone,validateCode);
            if (result.isFlag()) {
                //登录成功后写入cookie
                Cookie cookie = new Cookie("login_member_telephone", telephone);
                cookie.setMaxAge(30 * 60 * 60 * 24);//有效时间为30天
                cookie.setPath("/");//路径
                response.addCookie(cookie);
                //将查出的会员信息保存为json的字符串类型存到redis中，过期时间为30天
                String  member = JSON.toJSON(result.getData()).toString();//将member对象转换为json字符串
                jedisPool.getResource().setex(telephone,60*60*24*30,member);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.TellMember);
        }

        return  result;
    }

}
